import sys
import os
from config import config
import json
import time
from simple_chalk import chalk

# for chalk works
os.system("")


def pickToFirst(ls, val):
    if val in ls:
        ls.remove(val)
    ls.insert(0, val)

    return ls


def savePassResultToFile(user, book, dailyFile, isTest, config=config):
    resultFile = config["resultFile"]
    absResultFile = getAbsPath(resultFile)
    data = {}
    if os.path.exists(absResultFile):
        with open(absResultFile, "r", encoding="utf8") as f:
            data = json.load(f)

    data["lastUser"] = user
    data[user] = {
        "user": user,
        "book": book,
        "dailyFile": dailyFile,
        "date": str(time.strftime("%Y-%m-%d %H:%M:%S")),
        "isTest": isTest,
    }
    with open(absResultFile, "w", encoding="utf8") as f:
        json.dump(data, f)

    return True


def getLastResult():
    lastResult = {}
    absResultFile = getAbsPath(config["resultFile"])
    if os.path.exists(absResultFile):
        with open(absResultFile, "r", encoding="utf8") as f:
            lastResult = json.load(f)

    return lastResult


def getAbsPath(p):
    return os.path.abspath(os.path.join(__file__, r"..\%s" % p))


def getBooks():
    absBookDir = getAbsPath(config["bookDir"])
    return [dir.rstrip(".txt") for dir in os.listdir(absBookDir)]


def getAllDailyFiles():
    absDailyDir = getAbsPath(config["dailyDir"])
    return os.listdir(absDailyDir)


def getDailyFilesOfBook(book):
    files = getAllDailyFiles()
    return [fname for fname in files if fname.startswith(book)]


def getFileName(book, sn):
    return book + str(sn).rjust(3, "0") + ".txt"


def getBookContent(book):
    absBookPath = getAbsPath("%s/%s.txt" % (config.get("bookDir"), book))
    shortBookPath = absBookPath.replace(
        os.path.abspath(os.path.join(absBookPath, "../..")), ""
    )
    if not os.path.exists(absBookPath):
        print("短语合集 %s 不存在, 请检查输入" % shortBookPath)
        sys.exit(1)

    lines = []
    with open(absBookPath, "r", encoding="utf8") as f:
        lines = f.readlines()

    return lines


def getDailyFileContent(book, sn):
    fname = getFileName(book, sn)
    absFileName = getAbsPath("%s/%s" % (config["dailyDir"], fname))
    lines = []

    if not os.path.exists(absFileName):
        dirPath = os.path.abspath(os.path.join(absFileName, "../.."))
        shortFilePath = absFileName.replace(dirPath, "")
        print("短语文件 %s 不存在, 请检查输入" % shortFilePath)
        sys.exit(1)

    with open(absFileName, "r", encoding="utf8") as f:
        lines = f.readlines()

    return lines


def getFileNameByNum(isNumArg):
    numStr = sys.argv[1]
    numLs = list(numStr)
    alphaLs = [v for v in numLs if not v.isdecimal()]

    if isNumArg and len(alphaLs):
        print("参数不是全数字")
        return False

    numLs.insert(2, "U")
    fname = "phrase%s.txt" % "".join(numLs)

    return fname


def toGroups(ls, size=3):
    appendingTime = 1
    groups = []
    newGroup = []
    for i, v in enumerate(ls):
        if appendingTime > size:
            groups.append(newGroup)
            appendingTime = 1
            newGroup = []

        newGroup.append(v)
        appendingTime += 1
        if i == len(ls) - 1:
            groups.append(newGroup)

    return groups


def departToPhrases(lines):
    parts = []
    start = None
    end = None
    for index, line in enumerate(lines):
        line = line.strip()
        if line == "":
            # 开始空行都跳过
            if start is None:
                continue

            # 首次遇到空行，更新end
            if end is None:
                end = index
                parts.append(lines[start:end])
                start = None
        else:
            # 首次遇到非空行，更新start
            if start is None:
                start = index
                end = None

        # 末尾
        if index == len(lines) - 1:
            # 末尾为非空行
            if end is None:
                end = len(lines)
                parts.append(lines[start:end])

    return parts


def createDailyFile(phraseList, index, book):
    sn = index + 1
    fileName = getFileName(book, sn)
    absFilePath = getAbsPath("%s/%s" % (config.get("dailyDir"), fileName))

    phraseLs = ["".join(phrase) for phrase in phraseList]
    phraseCon = "\n".join(phraseLs)

    with open(absFilePath, "w", encoding="utf8") as f:
        f.write(phraseCon)

    print("write file ok:", absFilePath)


def createBookDailyFiles(book):
    lines = getBookContent(book)
    phraseList = departToPhrases(lines)
    groupList = toGroups(phraseList, config.get("dailyCount"))
    for index, group in enumerate(groupList):
        createDailyFile(group, index, book)

    print()
    print(chalk.yellow("短语集合 %s 已成功生成对应短语文件" % book))

    return True


if __name__ == "__main__":
    ls = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
    print(ls)
    print(toGroups(ls, 4))

    # fname = getFileName(True)
    # print(fname)
